package yang.yu.sunny.infra.elasticsearch;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import yang.yu.sunny.domain.product.Product;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yyang on 16/4/11.
 */
public class ProductSearcher extends AbstractSearcher {

    public ProductSearcher(Client client) {
        super(client);
    }

    public Product get(Long id) {
        GetResponse response = getClient()
                .prepareGet("mes", "product", id.toString())
                .get();
        try {
            return getObjectMapper().readValue(response.getSourceAsBytes(), Product.class);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<Product> findByName(String name) {
        SearchResponse response = getClient()
                .prepareSearch("mes")
                .setTypes("product")
                .setSearchType(SearchType.QUERY_AND_FETCH)
                .setQuery(QueryBuilders.matchQuery("name", name))
                //.setFrom(0).setSize(60).setExplain(true)
                .execute()
                .actionGet();
        List<Product> results = new ArrayList<>();
        for (SearchHit hit : response.getHits().getHits()) {
            try {
                Product product = getObjectMapper().readValue(hit.source(), Product.class);
                results.add(product);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return results;
    }

    public void create(Product product) {
        try {
            IndexResponse response = getClient()
                    .prepareIndex("mes", "product", product.getId().toString())
                    .setSource(getObjectMapper().writeValueAsBytes(product))
                    .get();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public void update(Product product) {
        try {
            UpdateResponse response = getClient()
                    .prepareUpdate("mes", "product", product.getId().toString())
                    .setSource(getObjectMapper().writeValueAsBytes(product))
                    .get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void remove(Long id) {
        DeleteResponse response = getClient()
                .prepareDelete("mes", "product", id.toString()).get();

    }
}
